<template>
  <a-card :bordered="false">
    <div class="card-title">{{ $route.meta.title }}</div>
    <a-spin :spinning="isLoading">
      <a-form :form="form" @submit="handleSubmit" :selfUpdate="true">
        <a-tabs :activeKey="tabKey" :tabBarStyle="{marginBottom: '30px'}" @change="handleTabs">
          <a-tab-pane :key="0" tab="基本信息"></a-tab-pane>
          <a-tab-pane :key="2" tab="图纸内容"></a-tab-pane>
        </a-tabs>
        <div class="tabs-content">
          <!-- 基本信息 -->
          <div class="tab-pane" v-show="tabKey == 0">

            <a-form-item label="图纸分类" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-tree-select
                placeholder="请选择图纸分类"
                :dropdownStyle="{ maxHeight: '500px', overflow: 'auto' }"
                :treeData="formData.categoryList"
                treeCheckStrictly
                allowClear
                v-decorator="['category_id', {rules: [{required: true, message: '请至少选择1个图纸分类'}]}]"
              ></a-tree-select>

              <div class="form-item-help">
                <router-link target="_blank" :to="{ path: '/goods/category/index' }">去新增</router-link>
                <a href="javascript:;" @click="onReloadCategoryList">刷新</a>
              </div>
            </a-form-item>

            <a-form-item label="图纸名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                placeholder="请输入图纸名称"
                v-decorator="['paper_name', {rules: [{required: true, min: 2, message: '请输入至少2个字符'}]}]"
              />
            </a-form-item>

            <a-form-item label="图纸编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入图纸编号" v-decorator="['paper_no']" />
            </a-form-item>
            <a-form-item
              label="封面图片"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              extra="建议尺寸：80*80"
            >
              <SelectImage
                :maxNum="1"
                field="path"
                v-decorator="['face', {rules: [{required: false, message: '请上传图纸封面'}]}]"
              />
              <p class="tip" style="clear:both">请将图片压缩后再上传,以油画用户体验，建议使用 :<a href="https://tinypng.com/" target="_blank">https://tinypng.com/</a>压缩后再上传</p>
            </a-form-item>
            <a-form-item
              label="图纸原图"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              extra="建议尺寸：文件不要太大,下载会很慢"
            >
              <SelectImage
                :maxNum="1"
                field="path"
                v-decorator="['source', {rules: [{required: false, message: '请上传图纸原图'}]}]"
              />
            </a-form-item>

            <a-form-item label="视频链接" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                placeholder="为了小程序能正常播放,请使用公众号里面上传的视频素材链接"
                v-decorator="['video', { rules: [{ required: false, min: 2, message: '请输入至少2个字符' }] }]"
              />
            </a-form-item>

            <a-form-item label="图纸状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-radio-group
                v-decorator="['status', {initialValue: 10, rules: [{ required: true }]}]"
              >
                <a-radio :value="10">上架</a-radio>
                <a-radio :value="20">下架</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item label="图纸排序" :labelCol="labelCol" :wrapperCol="wrapperCol" extra="数字越小越靠前">
              <a-input-number
                :min="0"
                v-decorator="['sort', {initialValue: 100, rules:[{ required: true }]}]"
              />
            </a-form-item>

          </div>

          <!-- 商品详情 -->
          <div class="tab-pane" v-show="tabKey == 2">
            <a-form-item label="图纸详情" :labelCol="labelCol" :wrapperCol="{span: 16}">
              <Ueditor v-decorator="['content', {rules: [{required: false, message: '详情不能为空'}]}]" />
            </a-form-item>
          </div>

        </div>
        <a-form-item class="mt-20" :wrapper-col="{ span: wrapperCol.span, offset: labelCol.span }">
          <a-button type="primary" html-type="submit" :loading="isBtnLoading">提交</a-button>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-card>
</template>

<script>
import * as GoodsApi from '@/api/paper'
import { SelectImage, Ueditor, InputNumberGroup } from '@/components'
import GoodsModel from '@/common/model/paper/Index'

export default {
  components: {
    SelectImage,
    Ueditor,
    InputNumberGroup
  },
  data () {
    return {
      // 默认的标签索引
      tabKey: 0,
      // 标签布局属性
      labelCol: { span: 3 },
      // 输入框布局属性
      wrapperCol: { span: 10 },
      // loading状态
      isLoading: false,
      isBtnLoading: false,
      // 当前表单元素
      form: this.$form.createForm(this),
      // 表单数据
      formData: GoodsModel.formData
    }
  },
  // 初始化数据
  created () {
    this.isLoading = true
    // 获取form所需的数据
    GoodsModel.getFromData()
      .then(() => {
        this.isLoading = false
      })
  },
  methods: {

    // 手动强制更新页面
    onForceUpdate (bool = false) {
      this.$forceUpdate()
      // bool为true时再执行一次 $forceUpdate, 特殊情况下需执行两次，原因如下：
      // 第一次执行 $forceUpdate时, 新元素绑定v-decorator无法获取到form.getFieldValue
      bool && setTimeout(() => {
        this.$forceUpdate()
      }, 10)
    },

    // 切换tab选项卡
    handleTabs (key) {
      this.tabKey = key
    },

    // 刷新分类列表
    onReloadCategoryList () {
      this.isLoading = true
      GoodsModel.getCategoryList().then(() => {
        this.isLoading = false
      })
    },

    /**
     * 确认按钮
     */
    handleSubmit (e) {
      e.preventDefault()
      // 表单验证
      const { form: { validateFields } } = this
      console.log(validateFields)
      validateFields((errors, values) => {
        // 定位到错误的tab选项卡
        if (errors) {
          this.onTargetTabError(errors)
          return false
        }
        // 提交到后端api
        this.onFormSubmit(values)
        return true
      })
    },

    /**
     * 定位到错误的tab选项卡
     */
    onTargetTabError (errors) {
      // 表单字段与tabKey对应关系
      // 只需要必填字段就可
      // const tabsFieldsMap = [
      //   ['paper_name', 'category_id', 'imagesIds', 'face'],
      //   ['content']
      // ]
      // const field = Object.keys(errors).shift()
      // for (const key in tabsFieldsMap) {
      //   if (tabsFieldsMap[key].indexOf(field) > -1) {
      //     this.tabKey = parseInt(key)
      //     break
      //   }
      // }
    },

    /**
    * 提交到后端api
    */
    onFormSubmit (values) {
      this.isLoading = true
      this.isBtnLoading = true
      GoodsApi.add({ form: values })
        .then(result => {
          // 显示提示信息
          this.$message.success(result.message, 1.5)
          // 跳转到列表页
          setTimeout(() => {
            this.$router.push('./index')
          }, 1500)
        })
        .catch(() => {
          this.isBtnLoading = false
        })
        .finally(() => {
          this.isLoading = false
        })
    }

  }
}

</script>
<style lang="less" scoped>
@import './style.less';
.tip{
 color: #ccc;
 font-size: 14px;
}
</style>
